<template>
  <view class="bg-[#f5f7fa] min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <!-- <PageHeader title="发布任务" :showBack="true" :onlyBack="true" /> -->
    <view class="fixed top-0 left-0 right-0 bg-white shadow-sm z-50">
      <view class="flex items-center px-[32rpx] py-[24rpx]">
        <view class="mr-[16rpx]" @tap="handleBack">
          <IconFont name="left" size="24" />
        </view>
       
        <view class="flex items-center">
          <image
            :src="getFullPath(chatInfo.avatar)"
            class="w-[60rpx] h-[60rpx] rounded-[30rpx] mr-[12rpx] bg-[#e0e0e0]"
             @error="handleAvatarError"
            mode="aspectFill"
          />
          <view>
            <text class="text-[28rpx] font-bold text-[#333]">{{ chatInfo.userName }}</text>
            <text class="text-[22rpx] text-[#999] block">{{ chatInfo.status }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <view ref="chatContainerRef" class="chat-container flex-1 px-[32rpx] pt-[150rpx] pb-[150rpx] overflow-y-auto">
      <!-- 连接状态提示 -->
      <view v-if="!webSocketStore.isConnected" class="flex justify-center mb-[32rpx]">
        <view class="bg-red-50 rounded-[20rpx] px-[24rpx] py-[12rpx] flex items-center gap-[16rpx]">
          <text class="text-[24rpx] text-red-500">
            {{ webSocketStore.isConnecting ? '正在连接...' : '连接已断开' }}
          </text>
          <view 
            v-if="!webSocketStore.isConnecting && webSocketStore.hasError" 
            class="bg-red-500 text-white px-[16rpx] py-[8rpx] rounded-[12rpx] text-[22rpx]"
            @click="handleReconnect"
          >
            重连
          </view>
        </view>
      </view>
      
      <!-- 欢迎消息 -->
      <view v-if="webSocketStore.isConnected" class="flex justify-center mb-[32rpx]">
        <view class="bg-blue-50 rounded-[20rpx] px-[24rpx] py-[12rpx]">
          <text class="text-[24rpx] text-blue-500">开始与 {{ chatInfo.userName }} 的对话</text>
        </view>
      </view>

      <!-- 聊天消息列表 -->
      <view class="flex flex-col gap-y-[24rpx]">
        <view
          v-for="(message, index) in messages"
          :key="index"
          class="flex items-end gap-x-[12rpx]"
          :class="message.isSelf ? 'justify-end' : 'justify-start'"
        >
          <!-- 对方头像 - 只在对方消息时显示 -->
          <view v-if="!message.isSelf" class="flex-shrink-0">
            <image
              :src="getFullPath(message.senderAvatar)"
              class="w-[60rpx] h-[60rpx] rounded-[30rpx]"
              mode="aspectFill"
              @error="handleAvatarError"
            />
          </view>
          
          <!-- 消息气泡 -->
          <view
            class="max-w-[70%] rounded-[20rpx] px-[24rpx] py-[16rpx]"
            :class="getMessageClass(message)"
          >
            <!-- 文本消息 -->
            <text v-if="message.type === 'text'" class="text-[26rpx] leading-[1.5]">{{ message.content }}</text>
            
            <!-- 图片消息 -->
            <view v-if="message.type === 'image'" class="w-full">
              <image
                :src="message.content"
                class="w-full max-w-[400rpx] rounded-[12rpx]"
                mode="widthFix"
                @click="handlePreviewImage(message.content)"
              />
            </view>
            
            <text class="text-[20rpx] opacity-70 block mt-[8rpx]">{{ message.time }}</text>
          </view>
          
          <!-- 自己头像 - 只在自己消息时显示 -->
          <view v-if="message.isSelf" class="flex-shrink-0">
            <image
              :src="message.senderAvatar || userAvatar"
              class="w-[60rpx] h-[60rpx] rounded-[30rpx]"
              mode="aspectFill"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 输入框区域 - 固定在底部 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-[#f0f0f0] px-[32rpx] py-[24rpx] z-50">
      <view class="flex items-center gap-x-[16rpx]">
        <!-- 图片上传按钮 -->
        <view 
          class="w-[60rpx] h-[60rpx] bg-gray-100 rounded-[30rpx] flex items-center justify-center"
          @click="handleUploadImage"
        >
          <IconFont 
            name="plus" 
            color="#666" 
            size="24" 
          />
        </view>
        
        <view class="flex-1 bg-[#f5f5f5] rounded-[24rpx] px-[24rpx] py-[16rpx]">
          <input
            v-model="inputMessage"
            class="text-[26rpx] text-[#333] w-full"
            placeholder="输入消息..."
            @confirm="handleSendMessage"
          />
        </view>
        
        <nut-button
          size="small"
          type="primary"
          class="bg-blue-500 border-none rounded-[24rpx] px-[24rpx] py-[16rpx]"
          @click="handleSendMessage"
        >
          <IconFont font-class-name="iconfont" class-prefix="icon" name="tuiguangzhongxin" color="#fff" size="16" />
        </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { useWebSocketStore } from "@/store/websocket";
import { useUserStore } from "@/store/user";
import { getFullPath, post } from "@/utils/request";
import ren from '@/assets/pic/ren.png'
import { getUserById } from "@/utils/comm";

// import { Button as nutButton } from "@nutui/nutui-taro";

/**
 * 聊天页面
 * 用于与申请用户进行沟通
 */

// 获取 stores
const webSocketStore = useWebSocketStore();
const userStore = useUserStore();

// 聊天信息
const chatInfo = ref({
  userId: "",
  userName: "用户",
  avatar: ren,
  status: "聊天中",
});

// 用户头像
const userAvatar = ref(userStore.userInfo.avatar_url || ren);

// 输入消息
const inputMessage = ref("");

// 聊天内容区域的引用
const chatContainerRef = ref(null);

const handleAvatarError = (event) => {
  event.target.src = ren;
};

// 计算属性：当前聊天室的消息
const messages = computed(() => {
  const currentUserId = userStore.userInfo.id;
  const targetUserId = chatInfo.value.userId;
  
  console.log('消息过滤调试信息:', {
    currentUserId,
    targetUserId,
    totalMessages: webSocketStore.messages.length,
    allMessages: webSocketStore.messages
  });
  
  if (currentUserId && targetUserId) {
    // 1对1聊天：根据from和to过滤消息
    const filteredMessages = webSocketStore.messages.filter(msg => {
      // 消息发送者是当前用户且接收者是目标用户，或者
      // 消息发送者是目标用户且接收者是当前用户
      const isRelevant = (msg.senderId == currentUserId && msg.receiverId == targetUserId) ||
                        (msg.senderId == targetUserId && msg.receiverId == currentUserId);
      
      console.log('消息过滤:', {
        msgId: msg.id,
        senderId: msg.senderId,
        receiverId: msg.receiverId,
        currentUserId,
        targetUserId,
        isRelevant
      });
      
      return isRelevant;
    });
    
    console.log('过滤后的消息数量:', filteredMessages.length);
    return filteredMessages;
  }
  return [];
});

// 计算属性：连接状态
const connectionStatus = computed(() => webSocketStore.connectionStatus);

/**
 * 返回上一页
 */
const handleBack = () => {
  console.log('handleBack')
  Taro.navigateBack();
};

/**
 * 手动重连
 */
const handleReconnect = async () => {
  try {
    console.log('用户手动重连');
    await webSocketStore.connect();
    // 重连成功后重新加载历史消息
    await loadHistoryMessages();
  } catch (error) {
    console.error("手动重连失败:", error);
    Taro.showToast({
      title: "重连失败，请检查网络",
      icon: "none",
      duration: 2000
    });
  }
};

/**
 * 获取消息样式类
 * @param {Object} message - 消息对象
 * @returns {string} 样式类名
 */
const getMessageClass = (message) => {
  const baseClass = "max-w-[70%] rounded-[20rpx] px-[24rpx] py-[16rpx]";
  
  if (message.isSelf) {
    return `${baseClass} bg-blue-500 text-white`;
  } else {
    return `${baseClass} bg-white text-gray-800 shadow-sm`;
  }
};

/**
 * 发送消息
 */
const handleSendMessage = () => {
  if (!inputMessage.value.trim()) {
    return;
  }

  if (!webSocketStore.isConnected) {
    Taro.showToast({
      title: "连接已断开，请重新连接",
      icon: "none",
      duration: 2000
    });
    return;
  }

  // 发送消息
  const success = webSocketStore.sendChatMessage(
    inputMessage.value,
    "text",
    chatInfo.value.userId
  );

  if (success) {
    // 清空输入框
    inputMessage.value = "";
    // 发送成功后滚动到底部
    scrollToBottom();
  } else {
    Taro.showToast({
      title: "发送失败，请重试",
      icon: "none",
      duration: 2000
    });
  }
};

/**
 * 上传图片
 */
const handleUploadImage = async () => {
  if (!webSocketStore.isConnected) {
    Taro.showToast({
      title: "连接已断开，请重新连接",
      icon: "none",
      duration: 2000
    });
    return;
  }

  try {
    const res = await Taro.chooseImage({
      count: 1, // 最多选择1张图片
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'] // 从相册选择或拍照
    });
    
    const tempFilePath = res.tempFilePaths[0];
    
    // 先上传图片到服务器
    const serverUrl = await uploadImageToServer(tempFilePath);
    console.log('serverUrl ==>', serverUrl)
    
    if (serverUrl) {
      // 发送服务器图片URL
      const success = webSocketStore.sendChatMessage(
        serverUrl,
        "image",
        chatInfo.value.userId
      );

      if (!success) {
        Taro.showToast({
          title: "发送图片失败，请重试",
          icon: "none",
          duration: 2000
        });
      } else {
        // 发送成功后滚动到底部
        scrollToBottom();
      }
    }
  } catch (err) {
    console.error('选择图片失败:', err);
    Taro.showToast({
      title: '选择图片失败',
      icon: 'none',
      duration: 2000
    });
  }
};

/**
 * 上传图片到服务器
 * @param {string} filePath - 本地文件路径
 * @returns {Promise<string>} 服务器图片URL
 */
const uploadImageToServer = async (filePath) => {
  try {
    Taro.showLoading({ title: '上传图片中...' });
    
    const uploadRes = await Taro.uploadFile({
      url: getFullPath('/file/upload'),
      filePath,
      name: 'file',
      header: {
        'token': Taro.getStorageSync('token') || ''
      }
    });
    
    Taro.hideLoading();
    
    const data = JSON.parse(uploadRes.data);
    if (data.code === 0) {
      Taro.showToast({ title: '图片上传成功', icon: 'success' });
      return getFullPath(data.data); // 返回服务器图片URL
    } else {
      Taro.showToast({ title: data.message || '图片上传失败', icon: 'none' });
      return null;
    }
  } catch (err) {
    Taro.hideLoading();
    Taro.showToast({ title: '图片上传失败', icon: 'none' });
    return null;
  }
};

/**
 * 预览图片
 * @param {string} imageUrl - 图片URL
 */
const handlePreviewImage = (imageUrl) => {
  Taro.previewImage({
    current: imageUrl,
    urls: [imageUrl]
  });
};

/**
 * 滚动到聊天区域底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainerRef.value) {
      const query = Taro.createSelectorQuery();
      query.select('.chat-container').boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec((res) => {
        if (res[0]) {
          Taro.pageScrollTo({
            scrollTop: res[0].height,
            duration: 300
          });
        }
      });
    }
  });
};

/**
 * 获取历史消息
 */
const loadHistoryMessages = async () => {
  try {
    const currentUserId = userStore.userInfo.id;
    const targetUserId = chatInfo.value.userId;
    
    if (!currentUserId || !targetUserId) {
      console.log('用户ID不完整，无法获取历史消息');
      return;
    }
    
    console.log('获取历史消息参数:', {
      fromUser: currentUserId,
      toUser: targetUserId
    });
    
    const response = await post('/message/getListById', {
      pageNo: 1,
      pageSize: 100,
      fromUser: parseInt(currentUserId),
      toUser: parseInt(targetUserId)
    });
    
    console.log('历史消息响应:', response);
    
    if (response.code === 0 && response.data) {
      // 将历史消息添加到WebSocket store中
      const historyMessages = response.data.map(item => {
        const msg = item.columns; // 获取实际的消息数据
        
        return {
          id: msg.id || Date.now().toString(),
          content: msg.content || '',
          type: msg.type || 'text',
          time: msg.create_time || new Date().toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" }),
          isSelf: msg.from_user === currentUserId,
          senderId: msg.from_user,
          receiverId: msg.to_user,
          senderName: msg.from_user_name,
          receiverName: msg.to_user_name,
          senderAvatar: msg.from_avatar_url,
          receiverAvatar: msg.to_avatar_url,
          status: msg.status
        };
      });
      
      // 清空当前消息列表，添加历史消息
      webSocketStore.clearMessages();
      historyMessages.forEach(msg => {
        webSocketStore.messages.push(msg);
      });
      
      console.log('历史消息加载完成，共', historyMessages.length, '条');
      console.log('添加到store的消息:', historyMessages);
      console.log('Store中的总消息数:', webSocketStore.messages.length);
      
      // 历史消息加载完成后滚动到底部
      nextTick(() => {
        scrollToBottom();
      });
    } else {
      console.log('获取历史消息失败:', response.message);
    }
  } catch (error) {
    console.error('获取历史消息出错:', error);
  }
};

// 页面加载时获取参数
onMounted(async () => {
  // 从路由参数获取用户信息
  const router = Taro.getCurrentInstance().router;
  console.log('router ==>', router)
  const { userId, userName } = router?.params || {};

  const userInfo = await getUserById(userId)
  if(!userInfo){
    Taro.showToast({
      title: "用户不存在",
      icon: "none",
      duration: 2000
    });
    return
  }
  chatInfo.value.userId = userInfo.id
  chatInfo.value.userName = userInfo.name
  chatInfo.value.avatar = userInfo.avatar_url
  chatInfo.value.status = "聊天中"

  // if (userId && userName) {
  //   chatInfo.value.userId = userId;
  //   chatInfo.value.userName = decodeURIComponent(userName);
  // }

  // 确保 WebSocket 连接
  try {
    console.log('聊天页面加载，建立WebSocket连接');
    await webSocketStore.connect();
    // 加载历史消息
    await loadHistoryMessages();
  } catch (error) {
    console.error("WebSocket 连接失败:", error);
    Taro.showToast({
      title: "连接失败，请检查网络",
      icon: "none",
      duration: 3000
    });
  }
});

// 监听消息列表变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// 页面卸载时清理
onUnmounted(() => {
  // 离开聊天页面时断开WebSocket连接，避免重复监听
  console.log('聊天页面卸载，断开WebSocket连接');
  webSocketStore.disconnect();
});
</script> 